package com.buddy.rpc.sdk.http;

import com.buddy.rpc.sdk.framework.Invocation;
import com.buddy.rpc.sdk.register.ServiceRegister;
import org.apache.commons.io.IOUtils;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author buddy
 * @date 2021/12/21
 */
public class HttpServiceHandler {
    public void handler(HttpServletRequest req, HttpServletResponse resp) {
        // 处理请求，返回结果
        try{
            ServletInputStream inputStream = req.getInputStream();
            ObjectInputStream ois = new ObjectInputStream(inputStream);

            Invocation invocation = (Invocation) ois.readObject();
            Class implClass = ServiceRegister.get(invocation.getInterfaceName());
            Method method = implClass.getMethod(invocation.getMethodName(),invocation.getParamTypes());
            String result = (String) method.invoke(implClass.newInstance(), invocation.getParams());
            IOUtils.write(result,resp.getOutputStream(),"utf-8");
        } catch (IOException | ClassNotFoundException | NoSuchMethodException
                | InstantiationException | IllegalAccessException
                | InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}
